<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // reduce的高级用法
        // 1.计算数组中每个元素出现的次数
        let arr = ['apple','pear','apple','car','school','car']
        let obj = arr.reduce((pre,current)=>{
            if(current in pre){
                pre[current]=pre[current]+1
            }else{
                pre[current] = 1
            }
            return pre  //得把当前的值返回回去
        },{})
        console.log(obj)
        // 2.数组去重
        let arr2= [1,2,3,4,4,1]
        let currentArr = arr2.reduce((pre,cur)=>{
            if(!pre.includes(cur)){
                return pre.concat(cur)
            }else{
                return pre
            }
        },[])
        console.log(arr2)

        // 3.数组对象累加
        var result = [
                {
                    subject: 'math',
                    score: 10
                },
                {
                    subject: 'chinese',
                    score: 20
                },
                {
                    subject: 'english',
                    score: 30
                }
            ];
        let sum = result.reduce((pre,cur)=>{
            return pre+cur.score
        },0)
        console.log(sum)

        // 4.将多维数组转化为一维
        let arr3 = [[0, 1], [2, 3], [4,[5,6,7]]]
        const newArr = function(arr){
            return arr.reduce((pre,cur)=>{
                if(Array.isArray(cur)){
                    return pre.concat(newArr(cur))
                }else{
                    return pre.concat(cur)
                }
            },[])
        }
        console.log(newArr(arr3))
    </script>
</body>
</html>